import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import {MaintainService} from "../../service/maintain.service";
import {MaintenanceService} from "../../service/maintenance.service";
import {Vehicle} from "../../model/vehicle";
import {MaintainRecord} from "../../model/maintainRecord";
declare var $:any;

@Component({
  selector: 'app-maintain-model',
  templateUrl: './maintain-model.component.html',
  styleUrls: ['./maintain-model.component.css']
})
export class MaintainModelComponent implements OnInit {

  userId:string = this.routerInfo.snapshot.queryParams["userId"];
  types:any;
  maintainForm:FormGroup;
  startPick:any;
  endPick:any;

  oid:string="";
  vehicleOid:string="";
  vehicleName:string="";
  licenseNumber:string="";
  flag:string="";
  vehicle:Vehicle;
  maintainRecord:MaintainRecord;
  disabledFlag:boolean = false;



  constructor(
    private router:Router,
    private routerInfo: ActivatedRoute,
    private fb:FormBuilder,
    private maintainService:MaintainService,
    private maintenanceService:MaintenanceService
    ) { }

  ngOnInit() {

    this.createForm();
    this.getTypes();

    //初始化开始时间
    this.startPick = $('#startDate').datetimepicker({
      // sideBySide: true, //可以同时选择日期和时间
      format: 'YYYY-MM-DD HH:mm',
      locale: 'zh-cn',
      ignoreReadonly: true,
      stepping: 30,        //设置最小间隔分钟数
      useCurrent: false,
    });
    this.startPick.on("dp.change", (e) => {
      //限制结束时间
      $('#endDate').data("DateTimePicker").minDate(e.date);
    });
    //初始化结束时间
    this.endPick = $('#endDate').datetimepicker({
      // sideBySide: true, //可以同时选择日期和时间
      format: 'YYYY-MM-DD HH:mm',
      locale: 'zh-cn',
      ignoreReadonly: true,
      stepping: 30,         //设置最小间隔分钟数
      useCurrent: false,
    });
    this.endPick.on("dp.change", (e) => {
      //限制开始时间
      $('#startDate').data("DateTimePicker").maxDate(e.date);
    });

    if(this.vehicle){
      this.maintainForm.patchValue({
        vehicle:this.vehicle.oid,
        vehicleName:this.vehicle.name,
        licenseNumber:this.vehicle.licenseNumber
      });
      $('#vehicleName').val(this.vehicle.name);
      $('#licenseNumber').val(this.vehicle.licenseNumber);
      if(this.flag==="edit" || this.flag==="view"){
        this.maintainForm.patchValue({
          oid:this.maintainRecord.oid,
          starttimeToString:this.maintainRecord.starttime.toString().substring(0,16),
          endtimeToString:this.maintainRecord.endtime.toString().substring(0,16),
          maintainType:this.maintainRecord.maintainType,
          maintainCost:this.maintainRecord.maintainCost,
          maintainItem:this.maintainRecord.maintainItem,
          description:this.maintainRecord.description
        });
      }
      if(this.flag==="view"){
        this.disabledFlag = true;
        this.maintainForm.patchValue({
          maintainType:this.maintainRecord.maintainTypeObj.name
        });
      }else{
        this.disabledFlag = false;
      }
    }
  }

  createForm(){
    this.maintainForm =this.fb.group({
      oid:'',
      vehicle:'',
      vehicleName:'',
      applicant:this.userId,
      licenseNumber:'',
      starttimeToString:'',
      endtimeToString:'',
      maintainType:'',
      maintainCost:'',
      maintainItem:'',
      description:''
    });
  }

  getTypes(){
    this.maintenanceService.getMaintenanceTypes().then(
      res=>{
        this.types = res;
      }
    );
  }

  //数据卡控
  checkData() {
    let msg = "";
    let reg = /^(0|[1-9][0-9]*)+(.[0-9]{1,2})?$/;	//判断只能为数字,且保留两位小数
    if(!$("#starttime").val()){
      msg +=("请选择开始时间！\n");
    }
    if(!$("#endtime").val()){
      msg +=("请选择结束时间！\n");
    }
    if(!$("#maintainType").val()){
      msg +=("请选择维护类型！\n");
    }
    if($("#maintainCost").val() && !reg.test($("#maintainCost").val())){
      msg +=("维护费用请填写数字，且小数点后只能保存两位！\n");
    }
    if(msg){
      alert(msg);
      return false;
    }else{
      return true;
    }
  }

  //保存记录
  onSubmit(){
    if(this.checkData()){
      this.maintainForm.patchValue({
        starttimeToString:$('#starttime').val(),
        endtimeToString:$('#endtime').val()
      });
      // console.log(this.maintainForm.value);
      if(this.flag==="add"){
        this.maintainService.createMaintainRecord(this.maintainForm.value).then(res=>{
          if(res.code ===1){
            alert(res.message);
            this.clearForm("n");
            this.maintainService.getRecordEvent.emit(["list"]);
          }else{
            alert(res.message);
          }
        });
      }else if(this.flag === "edit"){
        // console.log(this.maintainForm);
        this.maintainService.updateMaintainRecord(this.maintainForm.value).then(res=>{
          if(res.code ===1){
            alert(res.message);
            this.clearForm("n");
            this.maintainService.getRecordEvent.emit(["list"]);
          }else{
            alert(res.message);
          }
        });
      }
    }
  }

  //清空页面
  clearForm(flag){
    let xx = true;
    if(flag==="y") {
      xx = confirm("确认清空吗？");
    }
    if(xx){
      this.maintainForm.patchValue({
        applicant: this.userId,
        starttimeToString: '',
        endtimeToString: '',
        maintainType: '',
        maintainCost: '',
        maintainItem: '',
        description: ''
      });
    }
  }

}
